﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Xml.Serialization;

namespace TRPOP.Common
{
    /// <summary>
    /// 此类可以帮助自动序列化一系列的属性到字典中。
    /// 通常用于扩展一个类的属性，相应的数据里应该有一个ntext的字段对应。
    /// 在存储数值进数据库的时候，保存SerializedValue的数值，读取时，通过DeseriableExtendableObject方法来恢复字典。
    /// </summary>
    public class ExtendableObject
    {
        /// <summary>
        /// 数据字典
        /// </summary>
        public SerializableDictionary<string, object> _AttributesDictionary = new SerializableDictionary<string, object>();
        
        /// <summary>
        /// 
        /// </summary>
        public string SerializedValue
        {
            get
            {
                using (StringWriter sw = new StringWriter())
                {
                    XmlSerializer ser = new XmlSerializer(typeof(SerializableDictionary<string, object>));
                    ser.Serialize(sw, _AttributesDictionary);
                    return sw.ToString();
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        public void DeserilizeExtendableObject(string value)
        {
            if (string.IsNullOrEmpty(value))
                return;
            using (StringReader sr = new StringReader(value))
            {
                XmlSerializer xz = new XmlSerializer(typeof(SerializableDictionary<string, object>));
                _AttributesDictionary = (SerializableDictionary<string, object>)xz.Deserialize(sr);
            }
        }
    }
}
